package com.turingoal.license.checker;

import cn.hutool.core.net.NetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

/**
 * 工具类-》基础工具类-》一些工具类
 */
public final class TgLicenseUtil {
    private static final Logger logger = LoggerFactory.getLogger("licensej校验"); // 平台日志

    private TgLicenseUtil() {
        throw new Error("工具类不能实例化！");
    }

    /**
     * 字符串非空
     */
    static boolean isNotBlank(final String str) {
        return str != null && !str.isBlank();
    }

    /**
     * 反序列化<br>
     */
    static TgLicense deserialize(byte[] bytes) {
        TgLicense license = null;
        if (bytes != null && bytes.length > 0) {
            try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); TgObjectInputStream ois = new TgObjectInputStream(bis);) {
                license = (TgLicense) ois.readObject();
            } catch (IOException | ClassNotFoundException ex) {
                logger.debug("解析license文件失败！");
            }
        }
        return license;
    }

    /**
     * 读取字节流
     */
    static byte[] readBytes(final InputStream in) {
        byte[] content = null;
        BufferedInputStream bufIn = new BufferedInputStream(in);
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
        byte[] temp = new byte[1024];
        int size = 0;
        try {
            while ((size = bufIn.read(temp)) != -1) {
                out.write(temp, 0, size);
            }
            bufIn.close();
            content = out.toByteArray();
        } catch (IOException e) {
            logger.debug("读取license文件失败！");
        }
        return content;
    }

    /**
     * 获取所有本机Ip地址的方法(针对多网卡情况)
     */
    static List<String> getLocalIpList() throws Exception {
        List<String> ips = new ArrayList<>();
        String hostName = "";
        InetAddress addr;
        addr = InetAddress.getLocalHost();
        hostName = addr.getHostName();
        if (!hostName.isEmpty()) {
            InetAddress[] addrs;
            addrs = InetAddress.getAllByName(hostName);
            int length = addrs.length;
            if (length > 0) {
                for (InetAddress inetAddress : addrs) {
                    ips.add(inetAddress.getHostAddress());
                }
            }
        }
        return ips;
    }

    /**
     * 获得MAC地
     */
    public static List<String> getAllMacAddress() throws UnknownHostException {
        List<String> macs = new ArrayList<>();
        InetAddress addr = InetAddress.getLocalHost();
        if (addr != null) {
            String macsStr = NetUtil.getMacAddress(addr);
            if (TgLicenseUtil.isNotBlank(macsStr)) {
                macs = List.of(macsStr.split(","));
            }
        }
        return macs;
    }
}
